<template>
  <view class="content" v-if="isShow">
    <new-year-task-pop ref="newYearTask"></new-year-task-pop>
    <view class="top-message" v-if="!info">
      <daren :type="1" :index="0"></daren>
      发表
      <text>{{ config.publish_comment_word.conditions }}</text>
      字
      <text>+{{ config.publish_comment_word_picture.conditions }}</text>
      视频的优质评论，享
      <text>{{ config.publish_comment_word_picture.integral }}</text>
      积分呦
    </view>
    <view class="text-box">
      <view class="box">
        <!--        快捷指令-->
        <view class="tap">
          <view class="tap-item" :class="textHover.includes(item)?'tap-item-hover':''" @click="addText(item)"
                v-for="item in titleList">{{ item }}
          </view>
        </view>
        <!--        输入框-->
        <view class="textarea-box" v-if="textList.length===0">
          <view class="bj-text" v-if="!text">
            <image :src="image_host+'icon_penlic@2x.png'"></image>
            展开说说对话题的想法吧…
          </view>
          <view class="textarea">
            <textarea v-model="text"></textarea>
          </view>
        </view>
        <!--        快捷指令输入-->
        <view class="textarea-list" v-if="textList.length!==0">
          <view class="textarea-item" v-for="item in textList">
            <view class="bj-text2">{{ item.title }}</view>
            <view class="textarea2">
              <textarea v-model="item.text" auto-height></textarea>
            </view>
          </view>
        </view>
      </view>
      <view v-if="!info && !dayLimit" class="message-prompt" v-html="messagePrompt"></view>
      <view class="upload-box">
        <view class="upload-item" v-for="item in uploadList">
          <image mode="aspectFit" v-if="item.fileType==='video'" :src="item.thumbTempFilePath"></image>
          <image mode="aspectFit" v-if="item.fileType==='image'" :src="item.tempFilePath"></image>
          <view class="schedule" v-if="[0,1].includes(item.type)">{{ item.progress }}%</view>
          <view class="video-play" v-if="item.fileType==='video' && item.type===2">
            <image :src="image_host+'icon_play.png'"></image>
          </view>
        </view>
        <view class="upload-button" :class="uploadList.length===0?'upload-button-da':''" @click="uploadFile">
          <image mode="aspectFit" :src="image_host+'icon_intozhaopian@2x.png'"></image>
          <view>添加照片/视频</view>
        </view>
      </view>
    </view>
    <view class="bottom">
      <view class="message">
        <view class="message-icon">
          <image mode="aspectFit" :src="image_host+'q_icon_jifen@2x.png'"></image>
        </view>
        <view class="message-box">
          <view class="message-text-1">发布可领取积分呦</view>
          <!--          <view class="message-text-2">成功获取0积分</view>-->
        </view>
      </view>
      <view class="button" :class="(text.length-textListCount)>=10 && isSubmit?'button-hover':''">
        <view class="button-icon">
          <image mode="aspectFit" :src="image_host+'icon_fabu@2x.png'"></image>
        </view>
        <view class="button-text" @click="Submit">发布</view>
      </view>
    </view>
    <pop-message ref="popMessage">

      <view v-if="messageNum===1" style="text-align: center">今日领取积分已上限<br/>明天再接再厉哟</view>
      <view v-if="messageNum===2" style="text-align: center">
        本周再发
        <text>{{ returnData.fridayCondition - returnData.fridayNum }}</text>
        个图文或视频优质评价，可以领取
        <text>20</text>
        积分，和更多评论达人徽章值哟～
      </view>
      <view v-if="messageNum===3" style="text-align: center">发布成功</view>
      <view v-if="messageNum===4" style="text-align: center">
        本周累计发出了多个优质评论
        额外奖励您
        <text>20</text>
        积分哟
        并且还增加了评论达人值呦
        再接再厉
      </view>
      <!--      <view v-if="messageNum===3" style="text-align: center"></view>-->
    </pop-message>
  </view>
</template>

<script>
import Daren from "@/pages/circle/components/daren.vue";
import popMessage from "@/pages/circle/components/popMessage.vue";
import {uploadFile2} from "@/common/uploadCOS"
import NewYearTaskPop from "@/components/new-year-task-pop/new-year-task-pop.vue";

export default {
  components: {NewYearTaskPop, Daren, popMessage},
  data() {
    return {
      image_host: this.image_host + 'quanzi/',
      text: "",
      uploadList: [],
      imageCount: 0,
      videoCount: 0,
      textList: [],
      topicId: 0,
      config: {},
      titleList: [],
      textHover: [],
      messagePrompt: '',
      textListCount: 0,
      messageNum: "",
      info: "",
      scrollTopComment: 0,
      dayLimit: false,
      returnData: {},
      isSubmit: true,
      isShow: false
    };
  },
  onLoad(e) {
    this.topicId = e.id
    this.init(e.info, e.scrollTopComment)
  },
  onShow() {
    this.getIsShow()
  },
  watch: {
    textList: {
      handler(newArray, oblArray) {
        this.text = ''
        this.textListCount = 0
        this.textHover = newArray.map((item, index) => {
          this.textListCount += item.title.length
          this.text += item.text
          if (item.text.length < item.title.length) {
            this.textList.splice(index, 1)
          } else {
            return item.text1
          }
        })
      },
      deep: true
    },
    text: {
      handler(text) {
        if ((text.length - this.textListCount) < this.config.publish_comment_word.conditions) {
          let integral = this.config.publish_comment_word.integral
          let conditions = (this.config.publish_comment_word.conditions + this.textListCount) - text.length
          this.messagePrompt = `在写<span style="color: #C9623C">${conditions}</span>个字就可以获<span style="color: #C9623C">${integral}</span>积分`
        } else {
          if (this.videoCount === 0) {
            this.messagePrompt = `再上传<span style="color: #C9623C">${this.config.publish_comment_picture.conditions}</span>张图就可以获<span style="color: #C9623C">${this.config.publish_comment_picture.integral}</span>积分`
          } else {
            this.messagePrompt = ``
          }
        }
      },
      deep: true
    },
    uploadList: {
      handler(newArray, olbArray) {
        let imageCount = 0
        let videoCount = 0
        newArray.forEach(item => {
          if (item.fileType === 'image') {
            imageCount++
          } else if (item.fileType === 'video') {
            videoCount++
          }
        })
        this.imageCount = imageCount
        this.videoCount = videoCount
        if (videoCount > 0) {
          this.messagePrompt = ``
        }
        if (imageCount < this.config.publish_comment_picture.conditions && (this.text.length - this.textListCount) >= 10 && videoCount === 0) {
          let integral = this.config.publish_comment_picture.integral
          let conditions = this.config.publish_comment_picture.conditions - imageCount
          this.messagePrompt = `在上传<span style="color: #C9623C">${conditions}</span>张图就可以获<span style="color: #C9623C">${integral}</span>积分`
        } else {
          this.messagePrompt = ``
        }
      },
      deep: true
    }
  },
  methods: {
    // 是否显示发布话题
    async getIsShow() {
      let res = await this.$javaCircle.doRequest("post", "userservice/checkLine", '', '')
      this.isShow = !(res.data.data === null ? true : res.data.data);
    },
    async init(info, scrollTopComment) {
      let {data} = await this.$javaCircle.doRequest("get", 'circle/customer/comment/getCircleIntegralRuleList', '', '', false)
      data.data.list.forEach(item => {
        this.config[item.constantName] = item;
      })
      this.dayLimit = data.data.dayLimit
      uni.setStorageSync("toMessage", data.data.dayLimit)
      let integral = this.config.publish_comment_word.integral
      let conditions = (this.config.publish_comment_word.conditions + this.textListCount) - this.text.length
      this.messagePrompt = `输入<span style="color: #C9623C">${conditions}</span>个字就可以获<span style="color: #C9623C">${integral}</span>积分`
      let res = await this.$javaCircle.doRequest("get", 'circle/customer/comment/getTopicGuideSetup', {topicId: this.topicId}, '', false)
      this.titleList = res.data.data
      if (info) {
        this.info = JSON.parse(info)
        this.text = this.info.content
        console.log(this.info.picUrl)
        if (this.info.picUrl) {
          this.uploadList = this.info.picUrl.map(item => {
            item.type = 2;
            item.thumbTempFilePath = item.fileType === 'video' ? item.thumbUrl : '';
            item.tempFilePath = item.fileType === 'image' ? item.url : '';
            return item;
          })
          console.log(this.uploadList, 'this.uploadList')
        }
        this.scrollTopComment = scrollTopComment
        uni.setNavigationBarTitle({title: '修改评论'})
      }
      this.$forceUpdate()
    },
    addText(text) {
      if (this.textHover.includes(text)) {
        uni.showToast({title: '已存在', icon: "error"})
        return
      }
      let texts = text + ':'
      this.textList.push({title: texts, text: texts + '', text1: text})
    },
    uploadFile() {
      uni.chooseMedia({
        count: 9, // 最多选择的文件数量
        mediaType: ['image', 'video'], // 文件选择的类型，可以是图片、视频
        sourceType: ['album', 'camera'], // 文件选择的来源，可以是相册、相机
        success: (res) => {
          let list = res.tempFiles.map(item => {
            return {
              tempFilePath: item.tempFilePath,
              thumbTempFilePath: item.thumbTempFilePath,
              size: item.size,
              fileType: item.fileType,
              type: 0,//0 未上传，1上传中，2上传成功，3上传失败
              url: "",
              thumbUrl: "",
              progress: 0
            }
          })
          this.uploadList = this.uploadList.concat(list)
          this.uploadListOnChange(this.uploadList)
        }
      })
    },
    // 上传附件
    uploadListOnChange(list) {
      list.forEach((item, index) => {
        if (item.type === 0) {
          // 上传附件
          this.uploadList[index].type = 1
          let filename = item.tempFilePath.substr(item.tempFilePath.lastIndexOf('/') + 1);
          uploadFile2(item.tempFilePath, filename, item.size, progress => {
            this.uploadList[index].progress = parseInt(progress.percent * 100)
          }, false).then(res => {
            this.uploadList[index].type = 2
            this.uploadList[index].url = 'https://' + res.Location.replace("cos.ap-nanjing", "file");
          })
          if (!item.thumbTempFilePath) {
            return
          }
          // 上传视频第一针
          let filename1 = item.thumbTempFilePath.substr(item.thumbTempFilePath.lastIndexOf('/') + 1);
          uploadFile2(item.thumbTempFilePath, filename1, item.size, progress => {
          }, false).then(res => {
            this.uploadList[index].thumbUrl = 'https://' + res.Location.replace("cos.ap-nanjing", "file");
          })
        }
      })
    },
    // 发布评论
    async Submit() {
      if ((this.text.length - this.textListCount) < 10) {
        uni.showToast({title: '最少需要10个文字', icon: 'none'})
        return
      }
      if (!this.isSubmit) {
        console.log('重复点击')
        return
      }
      this.isSubmit = false
      let isFile = true;
      let postData = {
        topicId: this.topicId,
        content: this.text,
        picUrl: JSON.stringify(this.uploadList.map(item => {
          if (item.type !== 2) {
            isFile = false
          }
          return {fileType: item.fileType, url: item.url, thumbUrl: item.thumbUrl}
        })),
        from: uni.getStorageSync("taskId") === 3 ? 'task' : ''
      }
      if (!isFile) {
        this.isSubmit = true
        uni.showToast({title: '附件上传中...', icon: 'none'})
        return
      }
      if (this.info) {
        postData.commentId = this.info.id
      }
      let data = await this.$javaCircle.doRequest("post", 'circle/customer/comment/sendComment', postData, 'json', true)
      setTimeout(() => {
        this.isSubmit = true
      }, 2000)
      if (data.data.code !== 0) {
        uni.showToast({title: data.data.message, icon: 'none'})
        return
      }
      uni.setStorageSync("taskId", false)
      if (!data.data.data) {
        uni.reLaunch({url: '/pages/circle/details/details?id=' + this.topicId + '&scrollTopComment=' + this.scrollTopComment})
        return
      }
      uni.setStorageSync("saveMessage", this.topicId)
      this.returnData = data.data.data
      if (postData.from === 'task') {
        await this.$refs.newYearTask.show()
      }
      this.showMessage(data.data.data)
    },
    showMessage({firstNum, fridayCondition, fridayNum, integralNum}) {
      if (firstNum > 0) {
        this.$refs.popMessage.SshowComment()
        return
      }
      if (fridayCondition > fridayNum && fridayNum > 0) {
        this.messageNum = 2
        this.$refs.popMessage.showMessage3F()
        return;
      }
      if (fridayCondition === fridayNum && fridayCondition != null) {
        this.messageNum = 4
        this.$refs.popMessage.showMessage3F()
        return;
      }
      let toMessageTime = uni.getStorageSync("toMessage1")
      if (this.dayLimit && (toMessageTime < (new Date().getTime()))) {
        const todayEnd = new Date().setHours(23, 59, 59);
        uni.setStorageSync("toMessage1", todayEnd)
        this.messageNum = 1
        this.$refs.popMessage.showMessage3F()
        return;
      }
      uni.showToast({title: "发布成功", icon: "none"})
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  }
}
</script>

<style lang="scss">
page {
  width: 100%;
  height: 100%;
}

.content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding-bottom: 20upx;
}

.top-message {
  width: 100%;
  height: 68upx;
  background: linear-gradient(90deg, #FFF9F1 0%, #FAE9CD 100%);
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding-left: 20upx;
  font-size: 29upx;
  color: #241B0F;
  justify-content: space-between;

  text {
    color: #C9623C;
  }
}

.text-box {
  width: 100%;
  box-sizing: border-box;
  padding: 26upx 20upx;
  flex: 1;
}

.tap {
  display: flex;
  flex-wrap: wrap;
  column-count: 3;
  column-gap: 24upx;
}

.tap-item {
  box-sizing: border-box;
  padding: 6upx 22upx;
  color: #666666;
  border: 1upx solid #979797;
  margin-bottom: 24upx;
  border-radius: 31upx;
}

.textarea-box {
  position: relative;
  width: 100%;
}

.bj-text {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 40upx;
  color: #999999;
  display: flex;
  align-items: center;
  z-index: 1;

  image {
    width: 37upx;
    height: 37upx;
    margin-right: 8upx;
  }
}

.textarea {
  position: relative;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
  font-size: 40upx;
  z-index: 2;
  min-height: 200upx;

  textarea {
    width: 100%;
    min-height: 200upx;
  }
}

.upload-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  column-count: 3;
  column-gap: 12upx;
  margin-top: 50upx;
}

.upload-item {
  width: 222upx;
  height: 222upx;
  background-color: #F4F4F4;
  border-radius: 8upx;
  position: relative;
  margin-bottom: 12upx;

  image {
    width: 100%;
    height: 100%;
    border-radius: 8upx;
  }

  .schedule {
    position: absolute;
    top: 0;
    right: 0;
    width: 222upx;
    height: 222upx;
    background-color: rgba(0, 0, 0, .6);
    color: #00aaff;
    text-align: center;
    line-height: 222upx;
  }

  .video-play {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, .7);
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 62upx;
      height: 62upx;
    }
  }
}

.upload-button {
  width: 222upx;
  height: 222upx;
  background-color: #F4F4F4;
  border-radius: 8upx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 30upx;
  color: #999999;

  image {
    width: 70upx;
    height: 65upx;
    margin-bottom: 27upx;
  }
}

.upload-button-da {
  width: 100%;
}

.bottom {
  width: 100%;
  height: 130upx;
  box-sizing: border-box;
  padding: 0 30upx;
  display: flex;
  justify-content: space-between;
  margin-bottom: env(safe-area-inset-bottom);
}

.message {
  flex: 1;
  display: flex;
  align-items: center;
}

.message-icon {
  width: 42upx;
  height: 43upx;
  margin-right: 5upx;

  image {
    width: 100%;
    height: 100%;
  }
}

.message-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-bottom: 8upx;
}

.message-text-1 {
  font-size: 34upx;
  color: #333;
  font-weight: 500;
}

.message-text-2 {
  font-size: 30upx;
  color: #666666;
}

.button {
  width: 300upx;
  height: 130upx;
  border-radius: 80upx;
  background: linear-gradient(130deg, #C2E1CC 0%, #78C091 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 50upx;
  color: #fff;
  font-weight: 600;

  image {
    width: 42upx;
    height: 43upx;
    margin-right: 14upx;
  }
}

.textarea-item {
  width: 100%;
  position: relative;
  margin-bottom: 30upx;
}

.bj-text2 {
  font-size: 40upx;
  color: #999999;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  width: fit-content;
  background-color: #fff;
}

.textarea2 {
  width: 100%;
  position: relative;
  z-index: 1;

  textarea {
    width: 100%;
    font-size: 40upx;
    line-height: 50upx;
  }
}

.tap-item-hover {
  background-color: rgba(220, 255, 232, 1) !important;
  color: rgba(74, 177, 110, 1) !important;
  border: none;
}

.button-hover {

  background: linear-gradient(130deg, #4CB06A 0%, #4AB16E 100%) !important;
}
</style>
